<?php

namespace app\admin\controller;

use app\helpers\Common;
use app\common\model\AdminMenu;
use app\common\model\AdminRole;
use app\common\model\AdminRoleUser;

use support\Request;
use think\facade\Db;
use think\Exception;

class AdminRoleController extends BaseController
{

    public function initialize()
    {
        parent::initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere[] = ['status', '<>', 90];
        $this->defaultWhere = $defaultWhere;
    }

    /**
     * Save Post
     */
    protected function savePost($request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        if ($request->post()) {
            try {
                $data = self::evalData($request);
                $data['access'] = implode(',', $data['access']);

                if ($data['id']) {
                    // Update
                    $data['updated_at'] = time();
                    $result = $model->where('id', $data['id'])->update($data);

                    $msg = '保存成功!';
                    $logInfo = $this->admin['name'] . '更新了一条' . __($this->model) . '数据。';
                } else {
                    // Insert
                    $data['created_id'] = $data['updated_id'] = $this->admin['id'];
                    $data['created_at'] = time();
                    $result = $model->create($data);

                    $msg = '添加成功!';
                    $logInfo = $this->admin['name'] . '添加了一条' . __($this->model) . '数据。';
                }

                if ($result === false) {
                    return $this->error($msg, url('/' . $this->model . '/index'));
                }

                // 写入日志
                Common::adminLog($request, $logInfo);

                return $this->success($msg, url('/' . $this->model . '/index'));
            } catch (Exception $e) {
                return $this->error($e->getMessage(), url('/' . $this->model . '/index'));
            }
        }
    }

    /**
     * Delete
     */
    public function delete(Request $request)
    {
        $className = '\\app\\' . $this->appName . '\\model\\' . $this->model;
        $model = new $className;

        $id = $request->input('id');
        // 是否被使用
        $usedInfo = $this->isUsed($id);
        if ($usedInfo['code'] == 0) {
            return json([
                'code' => 0,
                'msg' => $usedInfo['msg']
            ]);
        }
        if ($usedInfo['code'] == 1) {
            $result = $model->where('id', $id)->delete();
        } elseif ($usedInfo['code'] == 2) {
            $result = $model->where('id', $id)->update(['deleted_id' => $this->admin['id'], 'deleted_at' =>time(), 'status' => 90]);
        }
        if ($result === false) {
            return $this->error('删除失败!', url('/' . $this->model . '/index'));
        }

        // 写入日志
        $logInfo = $this->admin['name'] . '删除了一条' . __($this->model) . '数据。';
        Common::adminLog($request, $logInfo);

        return $this->success('删除成功!', url('/' . $this->model . '/index'));
    }

    /**
     * 权限
     */
    public function getMenus(Request $request)
    {
        $param = $request->all();

        $access = [];
        if (isset($param['id'])) {
            $roleId = $param['id'];
            $access = AdminRole::where('id', $roleId)->value('access');
            $access = explode(',', $access);
        }

        $list = [];
        $recursive = function ($parentId) use (&$recursive, &$list, $access) {
            $where = [
                ['parent_id', '=', $parentId],
                ['status', '=', 1]
            ];
            $menus = AdminMenu::where($where)->field('id, name as title, parent_id')->order('sorting', 'ASC')->select()->toArray();
            foreach ($menus as $key => &$menu) {
                //$menu['spread'] = true; // 节点是否初始展开
                $menu['field'] = 'access[]';
                if (in_array($menu['id'], $access)) {
                    $menu['checked'] = true;
                }

                // 下级菜单
                $menu['children'] = $recursive($menu['id']);
                if ($parentId == 0) {
                    $list[] = $menu;
                }
            }

            return $menus;
        };

        $recursive(0);

        return json($list);
    }

    /**
     * 是否被使用过
     */
    protected function isUsed($id)
    {
        if (!$id) {
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 是否有管理员
        $admin = AdminRoleUser::where('role_id', $id)->field('id')->find();
        if ($admin) {
            return ['code' => 0, 'msg' => '该角色下有管理员，请先删除管理员'];
        }

        return ['code' => 1, 'msg' => ''];
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request)
    {
        $param = $request->all();
        $where = [];
        if (isset($param['name']) && $param['name']) {
            $where[] = ['name', 'like', '%' . trim($param['name']) . '%'];
        }
        if (isset($param['range_date']) && $param['range_date']) {
            $rangeDate = explode(' ~ ', $param['range_date']);
            $where[] = ['created_at', '>=', strtolower($rangeDate[0])];
            $where[] = ['created_at', '<=', strtotime($rangeDate[1])];
        }

        return $where;
    }
}
